package com.mobilepay.moneypig.model.application;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDexApplication;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.Preferences;
import com.mobilepay.moneypig.model.activity.home.PayCodeActivity;
import com.mobilepay.moneypig.model.activity.launcher.MainActivity;
import com.mobilepay.moneypig.response.mine.UserDetailData;
import com.mobilepay.moneypig.response.pro.UserInfo;
import com.mobilepay.moneypig.utils.LogDebug;
import com.mobilepay.moneypig.utils.PreferenceUtil;
import com.umeng.socialize.shareboard.ShareBoardConfig;

import java.lang.reflect.Type;
import java.util.Stack;

/**
 * Created by xlm on 2017/7/14 0014
 */

public class App extends MultiDexApplication {
    private Stack<Activity> mActivitys;
    protected static App mApp;
    public static MyHandler handler;
    public MainActivity mainActivity;
    public PayCodeActivity payCodeActivity;

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        newActivityStack();
        AppIntentService.start(mApp);//IntentService做初始化操作
        if (handler == null) {
            handler = new MyHandler();
        }
    }

    public boolean isFirstUse() {
        SharedPreferences preferences = getSharedPreferences(Preferences.FIRST_USE, MODE_PRIVATE);
        return preferences.getBoolean(Preferences.FIRST_USE, true);
    }

    public void setNotFirstUse() {
        SharedPreferences preferences = getSharedPreferences(Preferences.FIRST_USE, MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(Key.FIRST_USE, false);
        editor.commit();
    }

    public static ShareBoardConfig setShareBoard() {
        ShareBoardConfig shareBoardConfig = new ShareBoardConfig();
        shareBoardConfig.setShareboardBackgroundColor(Color.parseColor("#ffffff"));
        shareBoardConfig.setIndicatorVisibility(false);
        shareBoardConfig.setCancelButtonBackground(Color.parseColor("#f5f5f5"), Color.parseColor("#f5f5f5"));//normal press
        return shareBoardConfig;
    }

    public static void sendMessage(Message msg) {
        handler.sendMessage(msg);
    }

    @SuppressLint("HandlerLeak")
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (mainActivity != null) {
                        mainActivity.sendNotification((String) msg.obj);
                    }
                    if (payCodeActivity != null) {
                        payCodeActivity.finishPayCodeActivity();
                    }
                    break;
                case 1:
                    if (mainActivity != null) {
                        mainActivity.sendCliendId((String) msg.obj);
                    }
                    break;
            }
        }
    }

    private UserInfo mUserInfo;

    /**
     * app登陆后，保存userInfo
     *
     * @param userInfo
     */
    public void setUserInfo(UserInfo userInfo) {
        mUserInfo = userInfo;
        saveUserInfoToPrefrence(userInfo);
    }

    public UserInfo getUserInfo() {
        if (mUserInfo == null) {
            mUserInfo = getUserInfoFromPrefrence();
        }
        return mUserInfo;
    }

    /**
     * 注销
     */
    public void cancelAccount() {
        PreferenceUtil.setParam(this, Key.PASSWORD, "");
        setUserInfo(null);
        setUserDetailInfo(null);
    }

    /**
     * sava userInfo to preference
     *
     * @param userInfo
     */
    private void saveUserInfoToPrefrence(UserInfo userInfo) {
        SharedPreferences sharedPreferences = getSharedPreferences(Preferences.USERINFO, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (userInfo == null) {
            editor.putString(Key.USERINFO, "");
        } else {
            try {
                Gson gson = new Gson();
                String infoJson = gson.toJson(userInfo);
                editor.putString(Key.USERINFO, infoJson);
            } catch (Exception e) {
                LogDebug.e(e);
            }
        }
        editor.commit();
    }

    /**
     * get userInfo from preference
     *
     * @return
     */
    private UserInfo getUserInfoFromPrefrence() {
        SharedPreferences sharedPreferences = getSharedPreferences(Preferences.USERINFO, MODE_PRIVATE);
        String infoJson = sharedPreferences.getString(Key.USERINFO, "");
        try {
            Gson gson = new Gson();
            TypeToken<UserInfo> userInfoTypeToken = new TypeToken<UserInfo>() {
            };
            Type type = userInfoTypeToken.getType();
            return gson.fromJson(infoJson, type);
        } catch (Exception e) {
            LogDebug.e(e);
            return null;
        }
    }

    private UserDetailData detailData;

    /**
     * app登陆后，保存userInfo
     */
    public void setUserDetailInfo(UserDetailData detailData) {
        this.detailData = detailData;
        saveUserDetailInfoToPrefrence(detailData);
    }

    public UserDetailData getUserDetailInfo() {
        if (detailData == null) {
            detailData = getUserDetailInfoFromPrefrence();
        }
        return detailData;
    }

    /**
     * sava userInfo to preference
     */
    private void saveUserDetailInfoToPrefrence(UserDetailData detailData) {
        SharedPreferences sharedPreferences = getSharedPreferences(Preferences.USERDETAILINFO, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (detailData == null) {
            editor.putString(Key.USERDETAILINFO, "");
        } else {
            try {
                Gson gson = new Gson();
                String infoJson = gson.toJson(detailData);
                editor.putString(Key.USERDETAILINFO, infoJson);
            } catch (Exception e) {
                LogDebug.e(e);
            }
        }
        editor.commit();
    }

    /**
     * get userInfo from preference
     *
     * @return
     */
    private UserDetailData getUserDetailInfoFromPrefrence() {
        SharedPreferences sharedPreferences = getSharedPreferences(Preferences.USERDETAILINFO, MODE_PRIVATE);
        String infoJson = sharedPreferences.getString(Key.USERDETAILINFO, "");
        try {
            Gson gson = new Gson();
            TypeToken<UserDetailData> userInfoTypeToken = new TypeToken<UserDetailData>() {
            };
            Type type = userInfoTypeToken.getType();
            return gson.fromJson(infoJson, type);
        } catch (Exception e) {
            LogDebug.e(e);
            return null;
        }
    }

    /**
     * 获取application实例
     *
     * @return
     */
    public static App getApp() {
        return mApp;
    }

    /**
     * 创建activity栈
     */
    private void newActivityStack() {
        if (mActivitys == null) {
            mActivitys = new Stack<Activity>();
        }
    }

    /**
     * 获取activity栈
     *
     * @return
     */
    public Stack<Activity> getActivityStack() {
        return mActivitys;
    }


    /**
     * 结束所有activity
     */
    private void finishAllActivity() {
        while (!mActivitys.isEmpty()) {
            mActivitys.pop().finish();
        }
    }

    /**
     * 添加一个activity
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (!mActivitys.contains(activity)) {
            mActivitys.add(activity);
        }
    }

    /**
     * 移除一个activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (mActivitys.contains(activity)) {
            mActivitys.remove(activity);
        }
    }

    /**
     * 退出application
     */
    public void exitApplication() {
        exitApplication(true);
    }

    public void exitApplication(boolean needbackground) {
        finishAllActivity();
        if (!needbackground) {
            System.exit(0);
        }
    }

    public void finishTop() {
        if (!mActivitys.isEmpty()) {
            mActivitys.pop().finish();
        }
    }

}
